<template>
  <div class="media-input-container">
    <!-- 语音输入组件 -->
    <div class="voice-input-section">
      <div class="voice-controls">
        <el-button
          :type="isRecording ? 'danger' : 'primary'"
          :icon="isRecording ? 'VideoPause' : 'Microphone'"
          @click="toggleRecording"
          :loading="isProcessing"
          class="voice-button"
        >
          {{ isRecording ? '停止录音' : '开始录音' }}
        </el-button>
        
        <div v-if="isRecording" class="recording-indicator">
          <div class="recording-animation">
            <div class="wave"></div>
            <div class="wave"></div>
            <div class="wave"></div>
          </div>
          <span class="recording-time">{{ formatTime(recordingTime) }}</span>
        </div>
      </div>
      
      <!-- 录音结果 -->
      <div v-if="voiceResult" class="voice-result">
        <div class="result-header">
          <el-icon><ChatDotRound /></el-icon>
          <span>语音识别结果</span>
          <el-button size="small" text @click="clearVoiceResult">
            <el-icon><Close /></el-icon>
          </el-button>
        </div>
        <div class="result-content">
          <p>{{ voiceResult }}</p>
          <div class="result-actions">
            <el-button size="small" @click="insertVoiceText">
              <el-icon><Check /></el-icon>
              使用此文本
            </el-button>
            <el-button size="small" @click="playVoiceRecording" :disabled="!audioBlob">
              <el-icon><VideoPlay /></el-icon>
              播放录音
            </el-button>
          </div>
        </div>
      </div>
    </div>
    
    <!-- 图片上传组件 -->
    <div class="image-upload-section">
      <div class="upload-area">
        <el-upload
          ref="imageUploadRef"
          :auto-upload="false"
          :show-file-list="false"
          :on-change="handleImageChange"
          accept="image/*"
          drag
          multiple
          class="image-uploader"
        >
          <div class="upload-content">
            <el-icon class="upload-icon"><Picture /></el-icon>
            <div class="upload-text">
              <p>点击或拖拽图片到此处上传</p>
              <p class="upload-hint">支持 JPG、PNG、GIF 格式，单个文件不超过 10MB</p>
            </div>
          </div>
        </el-upload>
      </div>
      
      <!-- 图片预览 -->
      <div v-if="imageList.length > 0" class="image-preview-section">
        <div class="preview-header">
          <span>已选择图片 ({{ imageList.length }})</span>
          <el-button size="small" text @click="clearAllImages">
            <el-icon><Delete /></el-icon>
            清空
          </el-button>
        </div>
        <div class="image-preview-grid">
          <div 
            v-for="(image, index) in imageList" 
            :key="index" 
            class="image-preview-item"
          >
            <div class="image-wrapper">
              <img :src="image.url" :alt="image.name" @click="previewImage(image)" />
              <div class="image-overlay">
                <el-button 
                  size="small" 
                  type="primary" 
                  text 
                  @click="previewImage(image)"
                >
                  <el-icon><ZoomIn /></el-icon>
                </el-button>
                <el-button 
                  size="small" 
                  type="danger" 
                  text 
                  @click="removeImage(index)"
                >
                  <el-icon><Delete /></el-icon>
                </el-button>
              </div>
            </div>
            <div class="image-info">
              <div class="image-name">{{ image.name }}</div>
              <div class="image-size">{{ formatFileSize(image.size) }}</div>
            </div>
          </div>
        </div>
      </div>
    </div>
    
    <!-- 文件上传组件 -->
    <div class="file-upload-section">
      <div class="upload-area">
        <el-upload
          ref="fileUploadRef"
          :auto-upload="false"
          :show-file-list="false"
          :on-change="handleFileChange"
          accept=".pdf,.doc,.docx,.txt,.xlsx,.xls"
          drag
          multiple
          class="file-uploader"
        >
          <div class="upload-content">
            <el-icon class="upload-icon"><Document /></el-icon>
            <div class="upload-text">
              <p>点击或拖拽文件到此处上传</p>
              <p class="upload-hint">支持 PDF、Word、Excel、TXT 格式，单个文件不超过 50MB</p>
            </div>
          </div>
        </el-upload>
      </div>
      
      <!-- 文件列表 -->
      <div v-if="fileList.length > 0" class="file-list-section">
        <div class="file-list-header">
          <span>已选择文件 ({{ fileList.length }})</span>
          <el-button size="small" text @click="clearAllFiles">
            <el-icon><Delete /></el-icon>
            清空
          </el-button>
        </div>
        <div class="file-list">
          <div 
            v-for="(file, index) in fileList" 
            :key="index" 
            class="file-item"
          >
            <div class="file-icon">
              <el-icon><Document /></el-icon>
            </div>
            <div class="file-info">
              <div class="file-name">{{ file.name }}</div>
              <div class="file-details">
                <span class="file-size">{{ formatFileSize(file.size) }}</span>
                <span class="file-type">{{ getFileType(file.name) }}</span>
              </div>
            </div>
            <div class="file-actions">
              <el-button size="small" text @click="downloadFile(file)">
                <el-icon><Download /></el-icon>
              </el-button>
              <el-button size="small" type="danger" text @click="removeFile(index)">
                <el-icon><Delete /></el-icon>
              </el-button>
            </div>
          </div>
        </div>
      </div>
    </div>
    
    <!-- 上传操作按钮 -->
    <div v-if="hasFiles" class="upload-actions">
      <el-button 
        type="primary" 
        @click="uploadAllFiles" 
        :loading="uploading"
        :disabled="!hasFiles"
      >
        <el-icon><Upload /></el-icon>
        上传所有文件 ({{ totalFileCount }})
      </el-button>
      <el-button @click="clearAllMedia">
        <el-icon><RefreshLeft /></el-icon>
        清空所有
      </el-button>
    </div>
    
    <!-- 图片预览对话框 -->
    <el-dialog
      v-model="imagePreviewVisible"
      title="图片预览"
      width="80%"
      :before-close="closeImagePreview"
    >
      <div class="image-preview-dialog">
        <img :src="currentPreviewImage?.url" :alt="currentPreviewImage?.name" />
      </div>
      <template #footer>
        <el-button @click="closeImagePreview">关闭</el-button>
        <el-button type="primary" @click="downloadImage(currentPreviewImage)">
          <el-icon><Download /></el-icon>
          下载
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  Microphone,
  VideoPause,
  VideoPlay,
  ChatDotRound,
  Close,
  Check,
  Picture,
  Document,
  Upload,
  Download,
  Delete,
  ZoomIn,
  RefreshLeft
} from '@element-plus/icons-vue'

// Props
const props = defineProps({
  modelValue: {
    type: String,
    default: ''
  },
  maxFileSize: {
    type: Number,
    default: 10 * 1024 * 1024 // 10MB
  },
  maxFiles: {
    type: Number,
    default: 10
  }
})

// Emits
const emit = defineEmits(['update:modelValue', 'file-upload', 'voice-result'])

// 语音相关状态
const isRecording = ref(false)
const isProcessing = ref(false)
const recordingTime = ref(0)
const voiceResult = ref('')
const audioBlob = ref(null)
const mediaRecorder = ref(null)
const recordingTimer = ref(null)

// 文件相关状态
const imageList = ref([])
const fileList = ref([])
const uploading = ref(false)
const imagePreviewVisible = ref(false)
const currentPreviewImage = ref(null)

// 引用
const imageUploadRef = ref()
const fileUploadRef = ref()

// 计算属性
const hasFiles = computed(() => {
  return imageList.value.length > 0 || fileList.value.length > 0
})

const totalFileCount = computed(() => {
  return imageList.value.length + fileList.value.length
})

// 语音录音方法
const toggleRecording = async () => {
  if (isRecording.value) {
    stopRecording()
  } else {
    await startRecording()
  }
}

const startRecording = async () => {
  try {
    const stream = await navigator.mediaDevices.getUserMedia({ audio: true })
    
    mediaRecorder.value = new MediaRecorder(stream)
    const audioChunks = []
    
    mediaRecorder.value.ondataavailable = (event) => {
      audioChunks.push(event.data)
    }
    
    mediaRecorder.value.onstop = async () => {
      audioBlob.value = new Blob(audioChunks, { type: 'audio/wav' })
      
      // 模拟语音识别
      isProcessing.value = true
      try {
        await simulateVoiceRecognition()
      } finally {
        isProcessing.value = false
      }
      
      // 停止所有音频轨道
      stream.getTracks().forEach(track => track.stop())
    }
    
    mediaRecorder.value.start()
    isRecording.value = true
    recordingTime.value = 0
    
    // 开始计时
    recordingTimer.value = setInterval(() => {
      recordingTime.value++
    }, 1000)
    
    ElMessage.success('开始录音...')
  } catch (error) {
    ElMessage.error('无法访问麦克风，请检查权限设置')
    console.error('录音错误:', error)
  }
}

const stopRecording = () => {
  if (mediaRecorder.value && isRecording.value) {
    mediaRecorder.value.stop()
    isRecording.value = false
    
    if (recordingTimer.value) {
      clearInterval(recordingTimer.value)
      recordingTimer.value = null
    }
    
    ElMessage.success('录音结束')
  }
}

const simulateVoiceRecognition = async () => {
  // 模拟语音识别API调用
  await new Promise(resolve => setTimeout(resolve, 2000))
  
  const mockResults = [
    '我最近感觉头痛，想咨询一下医生',
    '请帮我预约明天上午的内科门诊',
    '我想了解一下高血压的预防方法',
    '最近总是失眠，有什么好的建议吗',
    '我的体检报告显示血糖偏高，需要注意什么'
  ]
  
  voiceResult.value = mockResults[Math.floor(Math.random() * mockResults.length)]
  emit('voice-result', voiceResult.value)
}

const playVoiceRecording = () => {
  if (audioBlob.value) {
    const audioUrl = URL.createObjectURL(audioBlob.value)
    const audio = new Audio(audioUrl)
    audio.play()
    
    audio.onended = () => {
      URL.revokeObjectURL(audioUrl)
    }
  }
}

const insertVoiceText = () => {
  emit('update:modelValue', props.modelValue + voiceResult.value)
  clearVoiceResult()
}

const clearVoiceResult = () => {
  voiceResult.value = ''
  audioBlob.value = null
}

// 图片处理方法
const handleImageChange = (file) => {
  if (!validateFile(file.raw, 'image')) return
  
  const reader = new FileReader()
  reader.onload = (e) => {
    imageList.value.push({
      name: file.name,
      size: file.size,
      url: e.target.result,
      file: file.raw
    })
  }
  reader.readAsDataURL(file.raw)
}

const previewImage = (image) => {
  currentPreviewImage.value = image
  imagePreviewVisible.value = true
}

const closeImagePreview = () => {
  imagePreviewVisible.value = false
  currentPreviewImage.value = null
}

const removeImage = (index) => {
  imageList.value.splice(index, 1)
}

const clearAllImages = () => {
  imageList.value = []
}

const downloadImage = (image) => {
  const link = document.createElement('a')
  link.href = image.url
  link.download = image.name
  link.click()
}

// 文件处理方法
const handleFileChange = (file) => {
  if (!validateFile(file.raw, 'file')) return
  
  fileList.value.push({
    name: file.name,
    size: file.size,
    file: file.raw
  })
}

const removeFile = (index) => {
  fileList.value.splice(index, 1)
}

const clearAllFiles = () => {
  fileList.value = []
}

const downloadFile = (file) => {
  const url = URL.createObjectURL(file.file)
  const link = document.createElement('a')
  link.href = url
  link.download = file.name
  link.click()
  URL.revokeObjectURL(url)
}

// 文件验证
const validateFile = (file, type) => {
  // 检查文件大小
  const maxSize = type === 'image' ? props.maxFileSize : 50 * 1024 * 1024 // 50MB for files
  if (file.size > maxSize) {
    ElMessage.error(`文件大小不能超过 ${formatFileSize(maxSize)}`)
    return false
  }
  
  // 检查文件数量
  const currentCount = type === 'image' ? imageList.value.length : fileList.value.length
  if (currentCount >= props.maxFiles) {
    ElMessage.error(`最多只能上传 ${props.maxFiles} 个文件`)
    return false
  }
  
  return true
}

// 上传所有文件
const uploadAllFiles = async () => {
  if (!hasFiles.value) return
  
  uploading.value = true
  
  try {
    const allFiles = [...imageList.value, ...fileList.value]
    
    // 模拟文件上传
    for (let i = 0; i < allFiles.length; i++) {
      await simulateFileUpload(allFiles[i])
    }
    
    ElMessage.success('所有文件上传成功！')
    emit('file-upload', { images: imageList.value, files: fileList.value })
    
    // 清空文件列表
    clearAllMedia()
  } catch (error) {
    ElMessage.error('文件上传失败，请重试')
    console.error('上传错误:', error)
  } finally {
    uploading.value = false
  }
}

const simulateFileUpload = async (file) => {
  // 模拟上传延迟
  await new Promise(resolve => setTimeout(resolve, 1000))
  return { success: true, url: 'https://example.com/uploaded/' + file.name }
}

const clearAllMedia = () => {
  clearAllImages()
  clearAllFiles()
  clearVoiceResult()
}

// 工具方法
const formatTime = (seconds) => {
  const mins = Math.floor(seconds / 60)
  const secs = seconds % 60
  return `${mins.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`
}

const formatFileSize = (bytes) => {
  if (bytes === 0) return '0 B'
  const k = 1024
  const sizes = ['B', 'KB', 'MB', 'GB']
  const i = Math.floor(Math.log(bytes) / Math.log(k))
  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
}

const getFileType = (filename) => {
  const ext = filename.split('.').pop().toLowerCase()
  const typeMap = {
    pdf: 'PDF',
    doc: 'Word',
    docx: 'Word',
    xls: 'Excel',
    xlsx: 'Excel',
    txt: 'Text'
  }
  return typeMap[ext] || ext.toUpperCase()
}

// 生命周期
onMounted(() => {
  // 检查浏览器支持
  if (!navigator.mediaDevices || !navigator.mediaDevices.getUserMedia) {
    ElMessage.warning('当前浏览器不支持语音录制功能')
  }
})

onUnmounted(() => {
  // 清理定时器
  if (recordingTimer.value) {
    clearInterval(recordingTimer.value)
  }
  
  // 停止录音
  if (isRecording.value) {
    stopRecording()
  }
})
</script>

<style scoped>
.media-input-container {
  background: white;
  border-radius: 12px;
  padding: 24px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
}

/* 语音输入样式 */
.voice-input-section {
  margin-bottom: 30px;
  padding-bottom: 20px;
  border-bottom: 1px solid #f0f0f0;
}

.voice-controls {
  display: flex;
  align-items: center;
  gap: 20px;
  margin-bottom: 15px;
}

.voice-button {
  min-width: 120px;
}

.recording-indicator {
  display: flex;
  align-items: center;
  gap: 15px;
}

.recording-animation {
  display: flex;
  gap: 3px;
  align-items: center;
}

.wave {
  width: 4px;
  height: 20px;
  background: #f56c6c;
  border-radius: 2px;
  animation: wave 1.5s ease-in-out infinite;
}

.wave:nth-child(2) {
  animation-delay: 0.2s;
}

.wave:nth-child(3) {
  animation-delay: 0.4s;
}

@keyframes wave {
  0%, 100% {
    height: 20px;
  }
  50% {
    height: 35px;
  }
}

.recording-time {
  font-family: 'Courier New', monospace;
  font-weight: 600;
  color: #f56c6c;
}

.voice-result {
  background: #f8f9fa;
  border-radius: 8px;
  padding: 16px;
  border-left: 3px solid #409eff;
}

.result-header {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 12px;
  font-weight: 600;
  color: #2c3e50;
}

.result-content p {
  margin: 0 0 12px 0;
  color: #2c3e50;
  line-height: 1.6;
}

.result-actions {
  display: flex;
  gap: 10px;
}

/* 上传区域样式 */
.image-upload-section,
.file-upload-section {
  margin-bottom: 30px;
}

.upload-area {
  margin-bottom: 20px;
}

.image-uploader,
.file-uploader {
  width: 100%;
}

.upload-content {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 40px 20px;
  text-align: center;
}

.upload-icon {
  font-size: 48px;
  color: #c0c4cc;
  margin-bottom: 16px;
}

.upload-text p {
  margin: 0;
  color: #606266;
}

.upload-text p:first-child {
  font-size: 16px;
  margin-bottom: 8px;
}

.upload-hint {
  font-size: 12px;
  color: #909399;
}

/* 图片预览样式 */
.image-preview-section,
.file-list-section {
  background: #f8f9fa;
  border-radius: 8px;
  padding: 16px;
}

.preview-header,
.file-list-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
  font-weight: 600;
  color: #2c3e50;
}

.image-preview-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(120px, 1fr));
  gap: 16px;
}

.image-preview-item {
  background: white;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.image-wrapper {
  position: relative;
  width: 100%;
  height: 120px;
  overflow: hidden;
}

.image-wrapper img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  cursor: pointer;
  transition: transform 0.3s;
}

.image-wrapper:hover img {
  transform: scale(1.05);
}

.image-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 10px;
  opacity: 0;
  transition: opacity 0.3s;
}

.image-wrapper:hover .image-overlay {
  opacity: 1;
}

.image-info {
  padding: 8px;
}

.image-name {
  font-size: 12px;
  color: #2c3e50;
  margin-bottom: 4px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.image-size {
  font-size: 11px;
  color: #909399;
}

/* 文件列表样式 */
.file-list {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.file-item {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 12px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.1);
}

.file-icon {
  font-size: 24px;
  color: #409eff;
}

.file-info {
  flex: 1;
}

.file-name {
  font-weight: 500;
  color: #2c3e50;
  margin-bottom: 4px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.file-details {
  display: flex;
  gap: 12px;
  font-size: 12px;
  color: #909399;
}

.file-actions {
  display: flex;
  gap: 8px;
}

/* 上传操作样式 */
.upload-actions {
  display: flex;
  justify-content: center;
  gap: 16px;
  padding-top: 20px;
  border-top: 1px solid #f0f0f0;
}

/* 图片预览对话框样式 */
.image-preview-dialog {
  text-align: center;
}

.image-preview-dialog img {
  max-width: 100%;
  max-height: 70vh;
  object-fit: contain;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .media-input-container {
    padding: 16px;
  }
  
  .voice-controls {
    flex-direction: column;
    align-items: stretch;
    gap: 12px;
  }
  
  .recording-indicator {
    justify-content: center;
  }
  
  .image-preview-grid {
    grid-template-columns: repeat(auto-fill, minmax(100px, 1fr));
    gap: 12px;
  }
  
  .image-wrapper {
    height: 100px;
  }
  
  .upload-actions {
    flex-direction: column;
  }
  
  .file-item {
    flex-direction: column;
    align-items: stretch;
    text-align: center;
  }
  
  .file-actions {
    justify-content: center;
  }
}
</style>